package com.promise.jokerdream.work.signin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 邪神秘宝工作
class TenlotteryWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "邪神秘宝"

    override val priority: Int
        get() = 3

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        // 先查询邪神秘宝信息
        val queryResult = gameApi.queryTenlottery()
        return queryResult.fold(
            onSuccess = { response ->
                // 检查紫色秘宝（advanced）是否有免费次数
                if (response.advanced.ifFree != 0) {
                    val purpleRewardResult = gameApi.rewardTenlottery(0) // 0为紫色
                    purpleRewardResult.fold(
                        onSuccess = { purpleResponse ->
                            historyManager.addHistory(name, purpleResponse.getDescription())
                        },
                        onFailure = { exception ->
                            historyManager.addHistory(name, exception.message)
                        }
                    )
                }

                // 检查橙色秘宝（extreme）是否有免费次数
                if (response.extreme.ifFree != 0) {
                    val orangeRewardResult = gameApi.rewardTenlottery(1) // 1为橙色
                    orangeRewardResult.fold(
                        onSuccess = { orangeResponse ->
                            historyManager.addHistory(name, orangeResponse.getDescription())
                        },
                        onFailure = { exception ->
                            historyManager.addHistory(name, exception.message)
                        }
                    )
                }

                WorkResult.Success
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
                WorkResult.Failure(exception, exception.message)
            }
        )
    }
}